<template>
	<el-upload list-type="picture-card" :action="action"
		accept="image/*"
		:show-file-list="false"
		:http-request="handleUpload"
		:before-upload="handleBefore"
		class="upload-picture-box">
		<div class="img-box">
			<img v-if="imgsrc" :src="imgsrc" />
			<i v-else-if="!uploadFlag" class="el-icon-plus"></i>
			<el-progress v-if="uploadFlag" type="circle"
				:width="76" 
				:height="76"
				:percentage="uploadPercent"
				style="position:absolute;top:0;left:0;margin:10px;">
			</el-progress>
		</div>
	</el-upload>
</template>

<script>
	/* 
	 * 图片上传组件
	 * value 绑定的值
	 */
	export default {
		name: 'DtUpload',
		props: {
			value: {
				type: String,
				default: null,
			},
			action: {
				type: String,
				default: '/upload',
			},
		},
		data() {
			return {
				imgsrc: null,
				uploadFlag: false,
				uploadPercent: 0
			}
		},
		methods: {
			//上传前检查
			handleBefore(file) {
				const isImg = /^image\/\w+$/i.test(file.type)
				if (!isImg) {
					this.$message.error('只能上传 JPG、PNG、GIF 格式!')
					return false
				}
				return true;
			},
			//上传文件
			handleUpload(item) {
				let _this = this;
				const formData = new FormData();
				formData.append("file", item.file);
				_this.$api.request({
					method: 'file',
					url: `${_this.action}`,
					data: formData,
					progress(event) {
						_this.handleProcess(event, item.file);
					},
					success(res) {
						_this.handleSuccess(res.data, item.file);
					},
				});
			},
			//上传成功
			handleSuccess(res, file) {
				this.uploadFlag = false;
				this.uploadPercent = 0;
				//拼接得到图片url
				const imageUrl = res[0].filePath;
				this.imgsrc = this.$api.loadFile(imageUrl);
				//触发事件 input，父组件会修改绑定的 value 值
				this.$emit('input', imageUrl);
			},
			//上传进度
			handleProcess(event, file) {
				this.uploadFlag = true;
				this.uploadPercent = Math.abs((event.loaded / event.total * 100).toFixed(0));
			}
		},
		watch: {
			value(newVal) {
				if (newVal) {
					this.imgsrc = this.$api.loadFile(newVal);
				}
			}
		},
	}
</script>

<style lang="scss">
	.upload-picture-box {
		.el-upload--picture-card {
			width: 98px;
			height: 98px;
			.img-box {
				display: flex;
				justify-content: center;
				align-items: center;
				width: 100%;
				height: 100%;
				img {
					margin: auto;
					max-width: 100%;
					max-height: 100%
				}
			}
		}
	}
</style>